package com.wmm.base;

import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;

public class BaseServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String methodName = null;

        //1.回去Post请求的 Content-Type类型
        String contentType = request.getHeader("Content-Type");

        //2.判断传递的数据是不是JSON格式
        if("application/json;charset=utf-8".equalsIgnoreCase(contentType)) {
            //是JSON格式  调用getPostJSON
            String postJSON = getPostJSON(request);

            //将JSON格式的字符串转换为map
            Map<String,Object> map = JSON.parseObject(postJSON, Map.class);

            //从map集合中获取methodName
            methodName = (String) map.get("methodName");
            //将获取到的数据，报讯到request域对象中
            request.setAttribute("map",map);
        } else {
            methodName = request.getParameter("methodName");
        }

        if (methodName != null){
            try {
                Class c = this.getClass();

                Method method = c.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);

                method.invoke(this,request,response);
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    /**
     * POST请求的格式为  ： application/json;charset=utf-8
     * 使用该方法进行读取
     */
    public String getPostJSON(HttpServletRequest request) {
        try {
            //1.从request中  获取缓冲输入流对象
            BufferedReader reader = request.getReader();

            //2.创建StringBuffer 保存读取出的数据
            StringBuffer sb = new StringBuffer();
            //3.循环读取
            String line = null;
            while((line = reader.readLine()) != null) {
                //将每次读取到的数据  最佳到StringBuffer里面
                sb.append(line);
            }

            //4.返回结果
            return sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
